import { constantRoutes } from '@/router'
import { getMenu } from '@/api/user'
import { validatenull } from '@/utils/validate'
import { setStore, getStore } from '@/utils/store'
/* Layout */
import Layout from '@/layout'

export const initMenu = (router, menu) => {
  if (menu.length === 0) {
    return
  }
  router.addRoutes(formatRoutes(menu))
}

export const formatRoutes = (aMenu) => {
  const aRouter = []
  aMenu.forEach(oMenu => {
    const {
      path,
      name,
      // component,
      icon,
      children
    } = oMenu

    const component = 'Layout'
    if (!validatenull(component)) {
      if (path === null) {
        console.log('path', path)
        console.log('name', name)
        console.log('--------------------------------------')
      }

      const oRouter = {
        path: path,
        component: (resolve) => {
          require([Layout], resolve)
          return
        },
        name: name,
        // hidden: true,
        meta: { title: name, icon: icon, affix: true },
        children: validatenull(children) ? [] : formatRoutes(children)
      }
      aRouter.push(oRouter)
    }
  })
  console.log(aRouter)
  return aRouter
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: getStore({ name: 'routes' }) || [],
  addRoutes: []
}

const mutations = {
  SET_ROUTERS: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    setStore({
      name: 'routes',
      content: state.routes,
      type: 'session'
    })
  }
}

const actions = {
  generateRoutes({ commit, state }, roles) {
    return new Promise(resolve => {
      getMenu().then((res) => {
        var accessedRouters

        var asyncRouterMap = formatRoutes(res.data)

        if (roles.indexOf('admin') >= 0) {
          accessedRouters = asyncRouterMap
        } else {
          accessedRouters = filterAsyncRoutes(asyncRouterMap, roles)
        }

        commit('SET_ROUTERS', accessedRouters)
        resolve(accessedRouters)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
